<template>
  <el-card class="swiper-container">
    <template #header>
      <div class="header">
        <div class="search-container">
          <el-input
              v-model="state.username"
              placeholder="请输入账号查询"
              clearable
              style="width: 200px; margin-left: 30px;margin-right: 10px"
          />
          <el-select
              v-model="state.role"
              placeholder="请选择角色"
              style="width: 170px;margin-right: 10px"
              class="category-selector">
            <el-option
                v-for="role in state.userRole"
                :key="role.id"
                :label="role.name"
                :value="role.id"/>
          </el-select>
          <el-button type="success" color="#71c4ef" @click="handleSearch">查询</el-button>
          <el-button type="success" color="#313d44" plain @click="handleReset">重置</el-button>
        </div>
        <hr>
        <el-button type="primary" :icon="Plus" @click="handleAdd">增加</el-button>
        <el-popconfirm
            title="确定删除吗？"
            confirmButtonText="确定"
            cancelButtonText="取消"
            @confirm="handleDelete"
        >
          <template #reference>
            <el-button type="danger" :icon="Delete">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
    </template>

    <el-table
        :loading="state.loading"
        ref="multipleTable"
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
    >
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          label="序号"
          align="center"
          width="120"
      >
        <template #default="scope">
          {{ (state.currentPage - 1) * state.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
          prop="username"
          label="账号"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="name"
          label="姓名"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="phone"
          label="电话"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="email"
          label="邮箱"
          align="center"
      >
      </el-table-column>
      <el-table-column
          label="头像"
          align="center"
          width="120">
        <template #default="scope">
          <img style="width: 80px;height: 80px;border-radius: 10px" :src="scope.row.avatar" alt="头像">
        </template>
      </el-table-column>
      <el-table-column
          prop="role"
          label="角色"
          align="center"
      >
      </el-table-column>

      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <div class="action-buttons">
            <!-- 编辑按钮 -->
            <el-button
                type="warning"
                size="small"
                :icon="Edit"
                :disabled="scope.row.id === '1'"
                @click="handleEdit(scope.row.id)">
              编辑
            </el-button>

            <!-- 删除按钮（带确认） -->
            <el-popconfirm
                title="确定要删除此项吗？"
                confirm-button-text="确认"
                cancel-button-text="取消"
                @confirm="handleDeleteOne(scope.row.id)"
            >
              <template #reference>
                <el-button
                    type="danger"
                    size="small"
                    :icon="Delete"
                    :disabled="scope.row.id === '1'"
                    style="margin-left: 8px">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @size-change="handleSizeChange"
        @current-change="changePage"
    />
  </el-card>
  <!--  编辑弹窗控件-->
  <UserInfoDialog ref='userInfoDialog' :reload="getIndexConfig" :type="state.type"
                  :configType="state.configType"/>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Plus, Delete, Edit} from '@element-plus/icons-vue';

const userInfoDialog = ref(null)
import {
  getUserById,
  listUsers,
  adduser,
  deleteUserById,
  deleteUserGroup,
  registerUser,
  updateUser,
  getLoginerInfo,
  logout
} from '../../service/userApi';
import UserInfoDialog from "../../components/UserInfoDialog.vue";

const state = reactive({
  username: '', // 新增搜索值
  role: '',       // 用户角色
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  currentPage: 1,
  pageSize: 5,
  type: 'add', // 操作类型
  total: 0, // 总条数
  userRole: [
    {id: '管理员', name: '管理员'},
    {id: '普通用户', name: '普通用户'},
  ]
});


onMounted(() => {
  getIndexConfig();
});

// 获取列表数据
const getIndexConfig = async () => {
  state.loading = true;
  try {
    const userPageDTO = {
      pageNum: state.currentPage,
      role: state.role,
      username: state.username,
      pageSize: state.pageSize,
    };
    const response = await listUsers(userPageDTO);
    // 提供默认值以防 response.data.records 或 response.data.total 为 null
    state.tableData = response.data.records || [];
    state.total = response.data.total || 0;
  } catch (error) {
    console.error("获取用户列表失败:", error);
    ElMessage.error("获取用户列表失败：" + error.message);
    state.tableData = []; // 清空表格数据
    state.total = 0; // 重置总条数
  } finally {
    state.loading = false;
  }
};

// 搜索处理
const handleSearch = () => {
  state.currentPage = 1;
  getIndexConfig();
};

// 重置处理
const handleReset = () => {
  state.role = '';
  state.username = '';
  state.currentPage = 1;
  getIndexConfig();
};

// 单个删除
const handleDeleteOne = async (id) => {
  try {
    await deleteUserById(id);
    ElMessage.success('删除成功');
    await getIndexConfig();
  } catch (error) {
    if (error.response && error.response.status === 404) {
      ElMessage.error('未找到资源，请检查 URL');
    } else {
      ElMessage.error('删除失败');
    }
    console.error('删除失败:', error);
  }
};

// 保存编辑
const saveEdit = async () => {
  try {
    const formattedEditInfo = {...editInfo};
    await updateUser(formattedEditInfo);
    ElMessage.success('编辑成功');
    isEditFormVisible.value = false;
    await getIndexConfig();
  } catch (error) {
    console.error('更新失败:', error);
    ElMessage.error('编辑失败');
  }
};

// 批量删除
const handleDelete = async () => {
  if (!state.multipleSelection.length) {
    ElMessage.error('请选择要删除的项');
    return;
  }
  const selectedIds = state.multipleSelection.map(item => item.id);
  try {
    // 显示确认删除提示框，显示要删除的记录数量
    await ElMessageBox.confirm(`确定要删除这 ${selectedIds.length} 条记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await deleteUserGroup(selectedIds);
    ElMessage.success('批量删除成功');
    await getIndexConfig(); // 刷新数据列表
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除操作
      return;
    }
    let errorMessage = '批量删除失败';
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage += `：${error.response.data.message}`;
    }
    ElMessage.error(errorMessage);
    console.error('批量删除失败:', error);
  }
};

// 分页处理
const changePage = (val) => {
  state.currentPage = val;
  getIndexConfig();
};

const handleSizeChange = (val) => {
  state.pageSize = val;
  state.currentPage = 1;
  getIndexConfig();
};

// 选中之后的change方法，一旦选项有变化，就会触发该方法
const handleSelectionChange = (val) => {
  state.multipleSelection = val;
};

// 添加用户
const handleAdd = () => {
  state.type = 'add'
  userInfoDialog.value.open();
};

// 编辑按钮
const handleEdit = async (id) => {
  state.type = 'edit'
  userInfoDialog.value.open(id);
};

// 头像上传成功回调
const handleAvatarSuccess = (response, file) => {
  if (isAddFormVisible.value) {
    newInfo.avatar = response.url;
  } else {
    editInfo.avatar = response.url;
  }
};

// 头像上传前校验
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return (isJPG || isPNG) && isLt2M;
};
</script>
<style>

</style>